import { Hono } from 'hono'
import { z } from 'zod'
import { SignatureService } from '@/services/signatureService'
import { getCurrentUser } from '@/middleware/auth'
import { asyncHandler, ValidationError } from '@/middleware/errorHandler'

const signature = new Hono()
const signatureService = new SignatureService()

// 验证模式
const generateKeyPairSchema = z.object({
  issuer: z.string().min(3).max(255)
})

const signPluginSchema = z.object({
  versionId: z.string(),
  keyId: z.string().optional()
})

const revokeCertificateSchema = z.object({
  keyId: z.string(),
  reason: z.string().min(10).max(500)
})

// 验证中间件
const validateJson = (schema: z.ZodSchema) => {
  return async (c: any, next: any) => {
    try {
      const body = await c.req.json()
      const validatedData = schema.parse(body)
      c.set('validatedData', validatedData)
      await next()
    } catch (error) {
      if (error instanceof z.ZodError) {
        throw new ValidationError(`Invalid request body: ${error.errors.map(e => e.message).join(', ')}`)
      }
      throw error
    }
  }
}

// 生成新的签名密钥对 (管理员功能)
signature.post('/certificates/generate',
  getCurrentUser,
  validateJson(generateKeyPairSchema),
  asyncHandler(async (c) => {
    const user = c.get('user')
    
    // 只有管理员可以生成证书
    if (user.role !== 'admin') {
      return c.json({
        success: false,
        error: { code: 'FORBIDDEN', message: 'Admin access required' }
      }, 403)
    }

    const { issuer } = c.get('validatedData')
    
    const keyPair = await signatureService.generateKeyPair(issuer)
    
    return c.json({
      success: true,
      data: {
        keyId: keyPair.keyId,
        publicKey: keyPair.publicKey,
        // 注意：不返回私钥
        message: 'Certificate generated successfully'
      },
      message: 'Signing certificate generated successfully'
    })
  })
)

// 为插件版本生成签名
signature.post('/sign',
  getCurrentUser,
  validateJson(signPluginSchema),
  asyncHandler(async (c) => {
    const user = c.get('user')
    const { versionId, keyId } = c.get('validatedData')
    
    // 只有管理员可以签名插件
    if (user.role !== 'admin') {
      return c.json({
        success: false,
        error: { code: 'FORBIDDEN', message: 'Admin access required' }
      }, 403)
    }

    const result = await signatureService.signPluginVersion(versionId, keyId)
    
    return c.json({
      success: true,
      data: result,
      message: 'Plugin version signed successfully'
    })
  })
)

// 验证插件签名
signature.get('/verify/:versionId',
  asyncHandler(async (c) => {
    const versionId = c.req.param('versionId')
    
    const result = await signatureService.verifyPluginSignature(versionId)
    
    return c.json({
      success: true,
      data: result,
      message: 'Signature verification completed'
    })
  })
)

// 获取证书信息
signature.get('/certificates/:keyId',
  asyncHandler(async (c) => {
    const keyId = c.req.param('keyId')
    
    const certificate = await signatureService.getCertificateInfo(keyId)
    
    if (!certificate) {
      return c.json({
        success: false,
        error: { code: 'NOT_FOUND', message: 'Certificate not found' }
      }, 404)
    }
    
    return c.json({
      success: true,
      data: certificate,
      message: 'Certificate information retrieved'
    })
  })
)

// 获取所有活跃证书 (管理员功能)
signature.get('/certificates',
  getCurrentUser,
  asyncHandler(async (c) => {
    const user = c.get('user')
    
    // 只有管理员可以查看所有证书
    if (user.role !== 'admin') {
      return c.json({
        success: false,
        error: { code: 'FORBIDDEN', message: 'Admin access required' }
      }, 403)
    }

    const certificates = await signatureService.getActiveCertificates()
    
    return c.json({
      success: true,
      data: { certificates },
      message: 'Active certificates retrieved'
    })
  })
)

// 撤销证书 (管理员功能)
signature.post('/certificates/:keyId/revoke',
  getCurrentUser,
  validateJson(revokeCertificateSchema),
  asyncHandler(async (c) => {
    const user = c.get('user')
    const keyId = c.req.param('keyId')
    const { reason } = c.get('validatedData')
    
    // 只有管理员可以撤销证书
    if (user.role !== 'admin') {
      return c.json({
        success: false,
        error: { code: 'FORBIDDEN', message: 'Admin access required' }
      }, 403)
    }

    await signatureService.revokeCertificate(keyId, reason)
    
    return c.json({
      success: true,
      message: 'Certificate revoked successfully'
    })
  })
)

// 批量验证插件签名 (管理员功能)
signature.post('/verify-batch',
  getCurrentUser,
  asyncHandler(async (c) => {
    const user = c.get('user')
    
    // 只有管理员可以批量验证
    if (user.role !== 'admin') {
      return c.json({
        success: false,
        error: { code: 'FORBIDDEN', message: 'Admin access required' }
      }, 403)
    }

    const body = await c.req.json()
    const versionIds = body.versionIds as string[]
    
    if (!Array.isArray(versionIds) || versionIds.length === 0) {
      throw new ValidationError('versionIds must be a non-empty array')
    }

    const results = await Promise.all(
      versionIds.map(async (versionId) => {
        try {
          const result = await signatureService.verifyPluginSignature(versionId)
          return { versionId, ...result }
        } catch (error) {
          return {
            versionId,
            isValid: false,
            keyId: '',
            algorithm: '',
            timestamp: 0,
            error: error instanceof Error ? error.message : 'Unknown error'
          }
        }
      })
    )
    
    return c.json({
      success: true,
      data: { results },
      message: 'Batch signature verification completed'
    })
  })
)

// 获取签名统计信息 (管理员功能)
signature.get('/stats',
  getCurrentUser,
  asyncHandler(async (c) => {
    const user = c.get('user')
    
    // 只有管理员可以查看统计
    if (user.role !== 'admin') {
      return c.json({
        success: false,
        error: { code: 'FORBIDDEN', message: 'Admin access required' }
      }, 403)
    }

    // 这里可以添加签名统计逻辑
    // 暂时返回基本信息
    const certificates = await signatureService.getActiveCertificates()
    
    return c.json({
      success: true,
      data: {
        activeCertificates: certificates.length,
        // 可以添加更多统计信息
      },
      message: 'Signature statistics retrieved'
    })
  })
)

export default signature
